<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

namespace App\Http\Controllers;

use App\Enums\PasswordQuestionEnum;
use App\Enums\UserIdentityEnum;
use App\Format\AdminUserFormat;
use App\Format\UserFormat;
use App\Format\UserProfileFormat;
use App\Http\Requests\ChangeUserRequest;
use App\Http\Requests\CheckRequest;
use App\Http\Requests\CreateAdminUserRequest;
use App\Http\Requests\CreateUserProfileFromAdminRequest;
use App\Http\Requests\ResetPasswrodRequest;
use App\Http\Requests\SetPassCardRequest;
use App\Http\Requests\SetUserProfileRequest;
use App\Http\Requests\UserLoginRequest;
use App\Http\Requests\UserRegRequest;
use App\Http\Requests\UserVcodeRequest;
use App\Http\Resources\UserForAdmin;
use App\Services\EnumDbService;
use App\Services\UserService;
use App\Traits\ExcelTrait;
use Illuminate\Http\Request;

class UserController extends Controller
{
    use ExcelTrait;

    protected $service;

    public function __construct(UserService $userService)
    {
        $this->service = $userService;
    }

    public function getQuestions()
    {
        $questions = PasswordQuestionEnum::toArray();
        $result = [];
        foreach ($questions as $type => $question) {
            array_push($result, [
                'password_question_type' => $type,
                'password_question_question' => $question,
            ]);
        }
        return renderSuccessJson($result);
    }

    public function reg(UserRegRequest $userRegRequest)
    {
        $isFlow = $userRegRequest->input('is_flow') == 1 ? true : false;
        $userFormat = new UserFormat($userRegRequest->all());
        $userToken = $this->service->reg($userFormat, $isFlow);
        return renderSuccessJson($userToken);
    }

    public function getVcode(UserVcodeRequest $userVcodeRequest)
    {
        $phone = $userVcodeRequest->input('phone');
        $vcode = $this->service->getVcode($phone);
        return renderSuccessJson($vcode);
    }

    public function getAdminVcode(UserVcodeRequest $userVcodeRequest)
    {
        $phone = $userVcodeRequest->input('phone');
        $vcode = $this->service->getAdminVcode($phone);
        return renderSuccessJson($vcode);
    }

    public function login(UserLoginRequest $userLoginRequest)
    {
        $phone = $userLoginRequest->input('phone');
        $hash = $userLoginRequest->input('hash');
        $loginRes = $this->service->login($phone, $hash);
        return renderSuccessJson($loginRes);
    }

    public function resetPassword(ResetPasswrodRequest $resertPasswrodRequest)
    {
        $phone = $resertPasswrodRequest->input('phone');
        $passwordQuestionAnswer = $resertPasswrodRequest->input('password_question_answer');
        $passwordQuestionType = $resertPasswrodRequest->input('password_question_type');
        $newPassword = $resertPasswrodRequest->input('new_password');
        $this->service->resetPassword($phone, $passwordQuestionType, $passwordQuestionAnswer, $newPassword);
        return renderSuccessJson();
    }

    /**
     * 用户提审自己的个人信息.
     *
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function setUserProfile(SetUserProfileRequest $setUserProfileRequest)
    {
        $format = new UserProfileFormat($setUserProfileRequest->all());
        $this->service->userPutProfileCheck($format);
        return renderSuccessJson();
    }

    public function changeUserInfo(ChangeUserRequest $changeUserRequest)
    {
        $format = new UserFormat($changeUserRequest->all());
        $format->setId($changeUserRequest->input('user_id'));
        $this->service->changeUserInfo($format);
        return renderSuccessJson();
    }

    /**
     * 其实这俩请求都是必须有 id...
     */
    public function getUserInfo(ChangeUserRequest $changeUserRequest)
    {
        $userId = (int)$changeUserRequest->input('id');
        return renderSuccessJson($this->service->getUserInfo($userId));
    }

    /**
     * 获取用户详细信息.
     */
    public function getUserProfile(Request $request)
    {
        $userId = $request->input('user_id');
        $profile = $this->service->getUserProfile($userId);
        return renderSuccessJson($profile);
    }

    public function getMyRentedHouse(Request $request)
    {
        $userId = $request->input('user_id');
        $res = $this->service->getMyRentedHouse($userId);
        return renderSuccessJson($res);
    }

    public function getIndustryList(EnumDbService $enumDbService, Request $request)
    {
        $search = [];
        if ($request->input('title')) {
            $search['title'] = $request->input('title');
        }
        $res = $enumDbService->getIndustry($search);
        return renderSuccessJson($res);
    }

    public function check(Request $checkRequest)
    {
        $id = $checkRequest->input('check_user_id');
        $checkStatus = $checkRequest->input('check_status');
        $checkMessage = $checkRequest->input('check_message') ?? '';
        $this->service->checkUserProfile($id, $checkStatus, $checkMessage);
        return renderSuccessJson();
    }

    public function saveUserProfileAsDraft(Request $request)
    {
        $format = new UserProfileFormat($request->all());
        $this->service->saveUserProfileAsDraft($format);
        return renderSuccessJson();
    }

    // 获取用户基本信息
    public function getUserDetail(Request $request)
    {
        $userProfileId = $request->input('user_profile_id');
        $res = $this->service->getUserDetail($userProfileId);
        return renderSuccessJson($res);
    }

    // 获取用户审核信息
    public function getUserCheckData(Request $request)
    {
        $userId = $request->input('handle_user_id');
        $res = $this->service->getUserCheckDetail($userId);
        return renderSuccessJson($res);
    }

    public function getUserProfileList(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);
        $search = [];
        if ($request->input('name')) {
            $search['name'] = $request->input('name');
        }
        if ($request->input('check_status')) {
            $search['check_status'] = $request->input('check_status');
        }
        if ($request->input('now_address')) {
            $search['now_address'] = $request->input('now_address');
        }
        if ($request->input('successive_not_in_village_days')) {
            $search['successive_not_in_village_days'] = $request->input('successive_not_in_village_days');
        }
        if ($request->input('area')) {
            $search['area'] = $request->input('area');
        }
        $res = $this->service->getAdminUserList($page, $pageSize, $search);
        return renderSuccessJson($res);
    }

    public function getNotFlowUser(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);
        $search = [];
        if ($request->input('name')) {
            $search['name'] = $request->input('name');
        }
        if ($request->input('check_status')) {
            $search['check_status'] = $request->input('check_status');
        }
        if ($request->input('now_address')) {
            $search['now_address'] = $request->input('now_address');
        }
        if ($request->input('successive_not_in_village_days')) {
            $search['successive_not_in_village_days'] = $request->input('successive_not_in_village_days');
        }
        if ($request->input('area')) {
            $search['area'] = $request->input('area');
        }
        $res = $this->service->getAdminNotFlowList($page, $pageSize, $search);
        return renderSuccessJson($res);
    }

    public function adminUpdateUserProfile(Request $request)
    {
        $format = new UserProfileFormat($request->all());
        $this->service->adminUpdateUserProfile($format);
        return renderSuccessJson();
    }

    public function createUserFromAdmin(CreateUserProfileFromAdminRequest $request)
    {
        $format = new UserProfileFormat($request->all());
        $this->service->createUserFromAdmin($format);
        return renderSuccessJson();
    }

    public function adminLogin(UserLoginRequest $userLoginRequest)
    {
        $phone = $userLoginRequest->input('phone');
        $hash = $userLoginRequest->input('hash');
        $loginRes = $this->service->adminLogin($phone, $hash);
        return renderSuccessJson($loginRes);
    }

    public function createAdminUser(CreateAdminUserRequest $createAdminUserRequest)
    {
        $format = new AdminUserFormat($createAdminUserRequest->all());
        $this->service->createAdminUser($format);
        return renderSuccessJson();
    }

    public function setPassCardInfo(SetPassCardRequest $setPassCardRequest)
    {
        $userId = $setPassCardRequest->input('user_id');
        $flowRegisterCode = $setPassCardRequest->input('flow_register_code');
        $passCardPhoto = $setPassCardRequest->input('pass_card_photo');
        $this->service->setPassCardInfo($flowRegisterCode, $passCardPhoto, $userId);
        return renderErrorJson();
    }

    public function getPassCardInfo(Request $request)
    {
        $userId = $request->input('user_id');
        $passCardInfo = $this->service->getPassCardInfo($userId);
        return renderSuccessJson($passCardInfo);
    }

    public function checkPassCard(CheckRequest $request)
    {
        $id = $request->input('id');
        $checkStatus = $request->input('check_status');
        $checkMessage = $request->input('check_message') ?? '';
        $this->service->checkPassCard($id, $checkStatus, $checkMessage);
        return renderSuccessJson();
    }

    public function houserList(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);
        $search = [];
        if ($request->input('name')) {
            $search['name'] = $request->input('name');
        }
        if ($request->input('need_check_house')) {
            $search['need_check_house'] = $request->input('need_check_house');
        }
        if ($request->input('order_column')) {
            $search['order_column'] = $request->input('order_column');
        }
        if ($request->input('order_type')) {
            $search['order_type'] = $request->input('order_type');
        }
        $res = $this->service->houserList($page, $pageSize, $search);
        return renderSuccessJson($res);
    }

    public function houserDetail(Request $request)
    {
        $houserId = $request->input('houser_id');
        $res = $this->service->houserDetail($houserId);
        return renderSuccessJson($res);
    }

    public function deleteUserProfile(Request $request)
    {
        $userProfileId = $request->input('user_profile_id');
        $this->service->deleteUserProfile($userProfileId);
        return renderSuccessJson();
    }

    public function updatePassword(Request $request)
    {
        $oldPassword = $request->input('old_password');
        $newPassword = $request->input('new_password');
        $userId = $request->input('user_id');
        $this->service->updatePassword($oldPassword, $newPassword, $userId);
        return renderSuccessJson();
    }

    public function setPosition(Request $request)
    {
        // 纬度
        $latitude = $request->input('latitude');
        // 经度
        $longitude = $request->input('longitude');

        $userId = $request->input('user_id');

        $this->service->setUserPosition($userId, $latitude, $longitude);
        return renderSuccessJson();
    }

    public function exportUserFromAdmin(Request $request)
    {
        $search = [];
        if ($request->input('name')) {
            $search['name'] = $request->input('name');
        }
        if ($request->input('check_status')) {
            $search['check_status'] = $request->input('check_status');
        }
        if ($request->input('now_address')) {
            $search['now_address'] = $request->input('now_address');
        }
        $search['identity'] = [UserIdentityEnum::FLOW_USER];

        if ($request->input('ids')) {
            $search['ids'] = explode(',', $request->input('ids'));
        }
        if ($request->input('successive_not_in_village_days')) {
            $search['successive_not_in_village_days'] = $request->input('successive_not_in_village_days');
        }
        if ($request->input('area')) {
            $search['area'] = $request->input('area');
        }

        $header = [
            'name' => '姓名',
            'phone' => '联系方式',
            'sex' => '性别',
            //'address' => '住址',
            'birthday' => '生日',
            'id_card_number' => '身份证',
            'native_place' => '籍贯',
            'marital_status' => '婚姻状态',
            'has_children' => '有无子女',
            'education' => '学历',
            'residence_place' => '户口所在地',
            'come_beijing_time' => '来村时间',
            'now_address' => '现居住地址',
            'company_name' => '公司名称',
            'industry' => '行业',
            'urgent_people' => '紧急联系人',
            'urgent_people_phone' => '紧急联系人电话',
            'has_contribution' => '有无贡献',
            //'contribution' => '具体贡献事迹',
            'has_violated' => '是否违纪',
            //'violated_detail' => '具体违纪事项',
            'identity' => '用户身份',
        ];

        $list = $this->service->getExportData($search);
        $res = UserForAdmin::collection($list);
        return $this->excelExport($header, $res->resolve(), '人口信息');
    }

    public function exportNotFlowUserFromAdmin(Request $request)
    {
        $search = [];
        if ($request->input('name')) {
            $search['name'] = $request->input('name');
        }
        if ($request->input('check_status')) {
            $search['check_status'] = $request->input('check_status');
        }
        if ($request->input('now_address')) {
            $search['now_address'] = $request->input('now_address');
        }
        if ($request->input('ids')) {
            $search['ids'] = explode(',', $request->input('ids'));
        }
        if ($request->input('successive_not_in_village_days')) {
            $search['successive_not_in_village_days'] = $request->input('successive_not_in_village_days');
        }
        if ($request->input('area')) {
            $search['area'] = $request->input('area');
        }
        $search['identity'] = [UserIdentityEnum::HOUSER, UserIdentityEnum::NORMAL];

        $header = [
            'name' => '姓名',
            'phone' => '联系方式',
            'sex' => '性别',
            //            'address' => '住址',
            'birthday' => '生日',
            'id_card_number' => '身份证',
            'native_place' => '籍贯',
            'marital_status' => '婚姻状态',
            'has_children' => '有无子女',
            'education' => '学历',
            'residence_place' => '户口所在地',
            'come_beijing_time' => '来村时间',
            'now_address' => '现居住地址',
            'company_name' => '公司名称',
            'industry' => '行业',
            'urgent_people' => '紧急联系人',
            'urgent_people_phone' => '紧急联系人电话',
            'has_contribution' => '有无贡献',
            //'contribution' => '具体贡献事迹',
            'has_violated' => '是否违纪',
            //'violated_detail' => '具体违纪事项',
            'identity' => '用户身份',
        ];

        $list = $this->service->getExportData($search);
        $res = UserForAdmin::collection($list);
        return $this->excelExport($header, $res->resolve(), '人口信息');
    }
}
